﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace H.Utils
{
    public static class BytesUtil
    {
        /// <summary>
        /// 将一个Int32数值转换为byte数组,并写入到buffer中去
        /// </summary>
        /// <param name="buffer">待写入的缓冲区</param>
        /// <param name="value">待写入的值</param>
        /// <param name="startIndex">开始写入的下标</param>
        public static void Write(this byte[] buffer, int value, int startIndex)
        {
            buffer[startIndex++] = (byte)(value & 0xFF);
            buffer[startIndex++] = (byte)((value >> 8) & 0xFF);
            buffer[startIndex++] = (byte)((value >> 16) & 0xFF);
            buffer[startIndex] = (byte)((value >> 24) & 0xFF);
        }

        /// <summary>
        /// 将一个Int32数值数组转换为byte数组,并写入到buffer中去,
        /// </summary>
        /// <param name="buffer">待写入的缓冲区</param>
        /// <param name="value">待写入的值</param>
        /// <param name="startIndex">开始写入的下标</param>
        public static void Write(this byte[] buffer, int[] value, int startIndex)
        {
            Write(buffer, value.Length, startIndex);
            for (int i = 0; i < value.Length; i++)
            {
                Write(buffer, value[i], startIndex + (i + 1) * 4);
            }
        }

        /// <summary>
        /// 将byte[]转换成int
        /// </summary>
        /// <param name="buffer">待读取的缓冲区</param>
        /// <param name="startIndex">开始读取的下标</param>
        /// <returns>返回读取到的Int32数据</returns>
        public static int GetInt(this byte[] buffer, int startIndex)
        {
            return buffer[startIndex] |
                (buffer[startIndex + 1] << 8) |
                (buffer[startIndex + 2] << 16) |
                (buffer[startIndex + 3] << 24);
        }

        /// <summary>
        /// 将从byte[]中读取一个int数组,以[长度+数组内容]编码
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <param name="startIndex">开始进行处理的下标</param>
        /// <returns>返回int数组</returns>
        public static int[] GetInts(this byte[] buffer, int startIndex)
        {
            int length = GetInt(buffer, startIndex);
            if (buffer.Length - startIndex < length * 4)
            {
                throw new IndexOutOfRangeException("传入的缓存区长度不足");
            }
            int[] ret = new int[length];
            for (int i = 0; i < length; i++)
            {
                startIndex += 4;
                ret[i] = GetInt(buffer, startIndex);
            }
            return ret;
        }

        /// <summary>
        /// 将缓冲区中的数据转换为UTF8字符串
        /// </summary>
        /// <param name="buffer">被读取的缓冲区</param>
        /// <param name="size">缓冲区中有效数据的长度</param>
        /// <returns>返回读取到的字符串</returns>
        public static string GetUTF8String(this byte[] buffer, int size)
        {
            return Encoding.UTF8.GetString(buffer, 0, size);
        }


    }
}
